package datastructure.day01;

/**
 * @author: Gan
 * @date 2021/4/27 0027 18:49
 * @description: 构建一个链表, 查找链表的中间元素
 **/
public class Linked1 {
    public static void main(String[] args) {
        int len = 0, count = 1;
        Node node1 = new Node("work");
        Node node2 = new Node("study");
        Node node3 = new Node("swim");
        Node node4 = new Node("play");
        Node node5 = new Node("movie");
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        Node p = node1;//设置一个指针在首元结点
        while (p != null) {
            len++;
            p = p.next;
        }

        p = node1;//指针回退

        if (len % 2 == 1) {
            while (p != null) {
                count++;
                p = p.next;
                if (count == (len / 2 + 1)) {
                    System.out.println(p.value);
                    return;
                }
            }
        } else {
            while (p != null) {
                count++;
                p = p.next;
                if (count == len / 2) {
                    System.out.println(p.value);
                    return;
                }
            }
        }

    }
}

class Node {
    String value;
    Node next;

    public Node(String value) {
        this.value = value;
    }
}